package net.lcqf.websocket.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;

import java.util.List;

/**
 * 消息解码器（解析Unity传输过来的数据）
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2021-2025 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2025/4/15 20:22
 * // +----------------------------------------------------------------------
 */

public class ProtobufDecoder extends MessageToMessageDecoder<WebSocketFrame> {

    @Override
    protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception {
        ByteBuf byteBuf = frame.content();

        // 读取大端长度前缀
        int length = byteBuf.readInt();
        byte[] protobufData = new byte[length];
        byteBuf.readBytes(protobufData);

        // 反序列化
        MsgInfoPojo.MsgInfo msgInfo = MsgInfoPojo.MsgInfo.parseFrom(protobufData);
        out.add(msgInfo);
    }
}
